#include "Utility.h"
#include "core.h"
#include <QFile>
#include <QTextCodec>
namespace CoreUtility
{
#ifndef NOT_USEQT
QJsonDocument openJsonDoc(const QString& filePath)
{
	if (QFile::exists(filePath))
	{
		QFile cfgFile(filePath);
		cfgFile.open(QIODevice::ReadOnly);
		QByteArray data = cfgFile.readAll();

		QJsonParseError err;
		QJsonDocument doc(QJsonDocument::fromJson(data, &err));
		if (doc.isNull()) {
			if (err.error == QJsonParseError::IllegalUTF8String) {
				QString string = QString::fromLocal8Bit(data);
				QByteArray bytes = string.toUtf8();
				QJsonDocument docUtf8(QJsonDocument::fromJson(bytes, &err));
				if (!docUtf8.isNull()) {
					doc = docUtf8;
				}

			}
		//	logError(MODULE_NAME, "Dev.cfg parse error! Offset:%d, code:%d, %s ", err.offset, err.error, err.errorString().toUtf8());
		}

		cfgFile.close();
		return doc;
	}
	return QJsonDocument();
}
#endif
int field_copy(char* dest, int capcity, const char* source, int len)
{
	// ss_strcpy_s 比ms的strcpy_s快50%,比ms的strcpy慢21%
	int i = 0;
	if (dest && capcity > 0)
	{
		if (source)//即使source为非法值,也会将dest阶段
		{
			if (len == -1)
			{
				while (*source && i + 1 < capcity)
				{
					dest[i++] = *source++;
				}
			}
			else if (len > 0)
			{
				while (*source && i + 1 < capcity && i < len)
				{
					dest[i++] = *source++;
				}
			}
			dest[i] = 0;//拷贝末尾截断
		}

		dest[capcity - 1] = 0;//范围末尾截断
	}
	return i;
}
int field_copyw(wchar_t* dest, int capcity, const wchar_t* source, int len)
{
	// ss_strcpy_s 比ms的strcpy_s快50%,比ms的strcpy慢21%
	int i = 0;
	if (dest && capcity > 0)
	{
		if (source)//即使source为非法值,也会将dest阶段
		{
			if (len == -1)
			{
				while (*source && i + 1 < capcity)
				{
					dest[i++] = *source++;
				}
			}
			else if (len > 0)
			{
				while (*source && i + 1 < capcity && i < len)
				{
					dest[i++] = *source++;
				}
			}
			dest[i] = 0;//拷贝末尾截断
		}

		dest[capcity - 1] = 0;//范围末尾截断
	}
	return i;
}
}

